<template>
  <div class="content-block">
      <div class="content-main">
        <div class="content-title">
          <div class="title-text-dot">职位列表</div>
          <div class="title-handle">
            <div class="handel-item">
              <el-button type="primary" size="mini" @click="handleAdd">新 增</el-button>
            </div>
            <div class="handel-item">
              <el-button type="primary" size="mini" @click="handleSearch">查 询</el-button>
            </div>
            <div class="handel-item">
              <el-input v-model="pTitle" size="mini" type="text" placeholder="职位名称"></el-input>
            </div>
          </div>
        </div>
        <el-table
          :data="positionList"
          border
          size="mini"
          height="calc(100vh - 230px)"
          v-loading="tableLoading"
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" :index="indexMethod" align="center" width="50"></el-table-column>
          <el-table-column label="职位名称" prop="pTitle"></el-table-column>
          <el-table-column label="职位类型" prop="pType"></el-table-column>
          <el-table-column label="招聘人数" prop="pNumber"></el-table-column>
          <el-table-column label="工作地址" prop="pAddr"></el-table-column>
          <el-table-column label="兼职薪资" prop="pWage">
             <template slot-scope="scope">
               <span>{{ formatMoney(scope.row.pWage) }}</span>
             </template>
          </el-table-column>
          <el-table-column label="工作开始时间" prop="pStart">
              <template slot-scope="scope">{{formatTime('yyyy-MM-dd hh:mm', scope.row.pStart)}}</template>
          </el-table-column>
          <el-table-column label="工作结束时间" prop="pEnd">
              <template slot-scope="scope">{{formatTime('yyyy-MM-dd hh:mm', scope.row.pEnd)}}</template>
          </el-table-column>
          <el-table-column label="工作时长" prop="duration"></el-table-column>
          <el-table-column label="兼职状态" prop="wuqStatus">
          <template slot-scope="scope">
            <span>{{ scope.row.pStatus | positionStatusName }}</span>
          </template>
        </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                title="编辑"
                class="text-blue"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="text"
                title="注销"
                class="text-red"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
        <!--操作弹窗-->
        <el-dialog
          :close-on-click-modal="false"
          :title="handleTitle"
          :visible.sync="handleVisible"
          width="60%"
          center
        >
          <el-form
            ref="positionForm"
            :model="positionForm"
            :rules="positionFormRule"
            status-icon
            label-width="90px"
            size="small"
          >
           <el-form-item label="企业名称" prop="cId">
              <el-select
                v-model="company"
                filterable
                clearable
                placeholder="请选择"
                value-key="wuqId"
                @change="handleInformer()"
              >
                <el-option
                  v-for="item in companyDown"
                  :key="item.wuqId"
                  :label="item.wuqTitle"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职位名称" prop="pTitle">
              <el-row>
                <el-col :span="24">
                  <el-input v-model.trim="positionForm.pTitle" type="text"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="职位类型" prop="pType">
                <el-select
                v-model="positionForm.pType"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in pTypeDown"
                  :key="item.enumId"
                  :label="item.enumName"
                  :value="item.enumId"
                ></el-option>
                </el-select>
            </el-form-item>
           <el-form-item label="招聘女性数量" prop="wNumber">
              <el-row>
                <el-col :span="24">
                  <el-input v-model.trim="positionForm.wNumber" type="number"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
              <el-form-item label="招聘男性数量" prop="mNumber">
              <el-row>
                <el-col :span="24">
                  <el-input v-model.trim="positionForm.mNumber" type="number"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="招聘总数量" prop="pNumber">
              <el-row>
                <el-col :span="24">
                  <el-input v-model.trim="positionForm.pNumber" type="number"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
              <el-form-item label="兼职薪资" prop="pWage">
              <el-row>
                <el-col :span="24">
                  <currency-input v-model.trim="positionForm.pWage"></currency-input>
                </el-col>
              </el-row>
            </el-form-item>
              <el-form-item label="结算方式" prop="settleType">
                  <el-select
                v-model="positionForm.settleType"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in settleTypeDown"
                  :key="item.enumId"
                  :label="item.enumName"
                  :value="item.enumId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="工作开始时间" prop="pStart">
               <el-date-picker
                      v-model="positionForm.pStart"
                      type="datetime"
                      format="yyyy-MM-dd hh:mm"
                      value-format="timestamp"
                      placeholder="选择开始时间"
                    ></el-date-picker>
            </el-form-item>
            <el-form-item label="工作结束时间" prop="pEnd">
             <el-date-picker
                      v-model="positionForm.pEnd"
                      type="datetime"
                      format="yyyy-MM-dd hh:mm"
                      value-format="timestamp"
                      placeholder="选择结束时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="招聘关键词" prop="pKeyword">
              <el-row>
                <el-col :span="24">
                  <el-input v-model.trim="positionForm.pKeyword" type="text"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="工作时长" prop="duration">
              <el-row>
                <el-col :span="24">
                  <el-input v-model.trim="positionForm.duration" type="text"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="招聘说明" prop="pExplain">
              <el-row>
                <el-col :span="24">
                   <tinymce-editor
                        v-model="positionForm.pExplain"
                        ref="pExplainEditor"
                      ></tinymce-editor>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="打卡范围" prop="allowedRange">
                <el-row>
                  <el-col :span="24">
                    <el-input v-model.trim="positionForm.allowedRange" type="text"></el-input>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="工作地址" prop="pAddr">
                <el-input v-model="positionForm.pAddr"></el-input>
                <el-button size="mini" type="primary" @click="getAddressKeyword"
                  >搜索</el-button>
                    <!-- 渲染地图的div容器 -->
                <div id="container"  style="width:100%; height:300px"></div>
              </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleVisible=false" size="mini">取 消</el-button>
            <el-button type="primary" @click="handleSave" size="mini">保 存</el-button>
          </div>
        </el-dialog>

        <!-- 删除弹窗 -->
        <el-dialog
          :close-on-click-modal="false"
          title="删除职位"
          :visible.sync="delVisible"
          width="260px"
          center
        >
          <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
          <span slot="footer" class="dialog-footer">
            <el-button size="mini" @click="delVisible = false">取 消</el-button>
            <el-button size="mini" type="danger" @click="deleteRow">删 除</el-button>
          </span>
        </el-dialog>
      </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
// 引入qqmap
import maps from 'qqmap'

// import the styles
export default {
  data() {
    const vm = this;
    let endDateRules = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入工作结束时间'));
      } else if (
        Date.parse(new Date(value)) <
        Date.parse(new Date(vm.positionForm.pStart))
      ) {
        callback(new Error('工作结束时间不能小于工作开始时间'));
      } else {
        callback();
      }
    };
    return {
      current: 1,
      pageSize: 10,
      total: 0,
      pId: '',
      pTitle: '',
      tableLoading: false,
      handleTitle: '',
      handleVisible: false,
      delVisible: false,
      showProgress: false,
      pTypeDown: [],
      settleTypeDown: [],
      enumType: '',
      company: {},
      positionForm: {
        pId: '',
        cId: '',
        pTitle: '',
        pType: '',
        wNumber: 0,
        mNumber: 0,
        pNumber: 0,
        pWage: 0,
        settleType: '',
        pStart: '',
        pEnd: '',
        pKeyword: '',
        pExplain: '',
        duration: 0,
        latitude: '',
        longitude: '',
        pAddr: '',
        allowedRange: ''
      },
      positionFormRule: {
        pTitle: [{ required: true, message:"请输入职位名称", trigger: "blur" }],
        pType: [{ required: true, message:"请选择职位类型", trigger: "blur" }],
        pNumber: [{ required: true, message:"请输入总人数", trigger: "blur" }],
        pWage: [{ required: true, message: "请输入兼职薪资", trigger: "blur" }],
        settleType: [{ required: true, message: "请选择结算方式", trigger: "blur" }],
        pStart: [{ required: true, message: "请选择工作开始时间", trigger: "change" }],
        pEnd: [{ required: true, validator: endDateRules, trigger: "change" }],
        pKeyword: [{ required: true, message:"请输入招聘关键词", trigger: "blur" }],
        pExplain: [{ required: true, message:"请输入招聘说明", trigger: "blur" }],
        duration: [{ required: true, message:"请输入工作时长", trigger: "blur" }],
        pAddr: [{ required: true, message:"请输入工作地点", trigger: "blur" }],
        allowedRange: [{ required: true, message:"请输入打卡范围", trigger: "blur" }],
      },
      map: null,
      getAddress: null,
      getAddCode: null,
      geocoder:[],
      markersArray:[],
    };
  },
  computed: {
    ...mapState({
      positionList: state => state.positionManage.positionList,
      companyDown: state => state.companyManage.companyDown,
    })
  },
  mounted() {
    this.getData();
    this.getEnum();
  },
  methods: {
    ...mapActions("companyManage", ["getCompanyDown"]),
    ...mapActions('enumManage', ['getEnumDown']),
    ...mapActions("positionManage", [
      "getPositionList",
      "getPositionById",
      "addPosition",
      "editPosition",
      "removePosition"
    ]),
    indexMethod(index) {
      return (this.current - 1) * this.pageSize + 1 + index;
    },
   async getEnum() {
      this.enumType = 'PT'
      // this.getEnumDown(this).then(res => {
      //   this.pTypeDown = res
      // })
      this.pTypeDown = await this.getEnumDown(this);
      this.enumType = 'ST'
      // this.getEnumDown(this).then(res => {
      //   this.settleTypeDown = res
      // })
      this.settleTypeDown = await this.getEnumDown(this);
    },
    getData() {
      this.tableLoading = true;
      this.getPositionList(this);
      this.getCompanyDown(this);
    },
    resetForm() {
      const vm = this;
      vm.positionForm = {
        pId: '',
        cId: '',
        pTitle: '',
        pType: '',
        wNumber: 0,
        mNumber: 0,
        pNumber: 0,
        pAddr: '',
        pWage: 0,
        settleType: '',
        pStart: '',
        pEnd: '',
        pKeyword: '',
        pExplain: '',
        duration: 0,
        latitude: '',
        longitude: '',
        pAddr: '',
        allowedRange: ''
      };
      vm.$nextTick(() => {
        vm.$refs.positionForm.clearValidate();
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getData();
    },
    handleSearch() {
      this.current = 1;
      this.getData();
    },
    handleAdd() {
      const vm = this;
      vm.resetForm();
      vm.handleVisible = true;
      vm.handleTitle = "新增职位";
      vm.init();
      vm.userInfo = {}
    },
    async handleEdit(row) {
      const vm = this;
      vm.resetForm();
      vm.handleVisible = true;
      vm.handleTitle = "编辑职位";
      vm.pId = row.pId
      let res = await vm.getPositionById(vm)
      vm.positionForm = {
        pId: res.pId,
        cId: res.cId,
        pTitle: res.pTitle,
        pType: res.pType,
        wNumber: res.wNumber,
        mNumber: res.mNumber,
        pNumber: res.pNumber,
        pWage: res.pWage,
        settleType: res.settleType,
        pStart: res.pStart,
        pEnd: res.pEnd,
        pKeyword: res.pKeyword,
        pExplain: res.pExplain,
        duration: res.duration,
        latitude: res.latitude,
        longitude: res.longitude,
        pAddr: res.pAddr,
        allowedRange: res.allowedRange
      };
      vm.init();
       
    },
    handleDelete(row) {
      this.pId = row.pId;
      this.delVisible = true;
    },
    handleInformer() {
      this.positionForm.cId = this.company.wuqId
      this.positionForm.latitude = this.company.wuqLatitude
      this.positionForm.longitude = this.company.wuqLongitude
      this.positionForm.pAddr = this.company.wuqArea
      this.positionForm.allowedRange = this.company.allowedRange
    },
    deleteRow() {
      this.removePosition(this);
    },
    handleSave() {
      const vm = this;
      vm.getAddressDetails(vm.positionForm.pAddr).then(res => {
        vm.positionForm.latitude = res.lat;
        vm.positionForm.longitude = res.lng;
      });
      if(vm.positionForm.latitude == '' || vm.positionForm.longitude === undefined
      || vm.positionForm.longitude == '' || vm.positionForm.longitude === undefined){
          vm.$message.error('输入地址不正确或获取经纬度有误，请重新输入或搜素地址')
          return false;
      }
      vm.$refs["positionForm"].validate(valid => {
        if (valid) {
          if (vm.handleTitle === "新增职位") {
            vm.addPosition(vm);
          } else {
            vm.editPosition(vm);
          }
        } else {
          return false;
        }
      });
    },
      init() {
        var vm = this;
        maps.init("W3YBZ-NW734-APUUL-XQTC4-76L2T-NCF70", () => {
          var myLatlng = new qq.maps.LatLng(34.23053, 108.93425);
          var myOptions = {
            zoom: 16,
            center: myLatlng,
            mapTypeId: qq.maps.MapTypeId.ROADMAP
          };
          vm.map = new qq.maps.Map(
            document.getElementById("container"),
            myOptions
          );
          //获取点击后的地址
          qq.maps.event.addListener(vm.map, "click", function(event) {
            // 获取点击后的地图坐标
            vm.positionForm.longitude = event.latLng.getLng();
            vm.positionForm.latitude = event.latLng.getLat();
            vm.getAddressCode();
          });

          //调用地址显示地图位置并设置地址
          vm.getAddress = new qq.maps.Geocoder({
            complete: function(result) {
              vm.map.setCenter(result.detail.location);
              vm.positionForm.longitude = result.detail.location.lng;
              vm.positionForm.latitude = result.detail.location.lat;
              var marker = new qq.maps.Marker({
                map: vm.map,
                position: result.detail.location
              });
              vm.markersArray.push(marker);
              if (vm.markersArray.length > 1) {
                  for (let i = 0; i < vm.markersArray.length - 1; i++) {
                      vm.markersArray[i].setMap(null);// 清除标记
                  }
              }
            }
          });
          //通过坐标来显示地图地址
          vm.getAddCode = new qq.maps.Geocoder({
            complete: function(result) {
              vm.positionForm.pAddr = result.detail.address;
            }
          });
        });
      },
      getAddressDetails(address){
        return new Promise((resolve, reject) => {
          maps.init("W3YBZ-NW734-APUUL-XQTC4-76L2T-NCF70", () => {
            let geocoder =  new qq.maps.Geocoder();
            geocoder.getLocation(address);
            geocoder.setComplete(res => {
              resolve({lng:res.detail.location.lng, lat:res.detail.location.lat});  
            });
            geocoder.setError(()=>{
              resolve({lng:"", lat:""});  
            });
          });
        });
      },
      //通过地址获得位置
      getAddressKeyword() {
        //通过getLocation();方法获取位置信息值
        this.getAddress.getLocation(this.positionForm.pAddr);
      },
      // 通过坐标获得地址
      getAddressCode() {
        var lat = parseFloat(this.positionForm.latitude);
        var lng = parseFloat(this.positionForm.longitude);
        var latLng = new qq.maps.LatLng(lat, lng);
        //调用获取位置方法
        this.getAddCode.getAddress(latLng);
      }
  }
};
</script>


